﻿using System;
using UnityEngine;
using UnityEngine.SceneManagement;

#if UNITY_EDITOR
using UnityEditor;
using UnityEditor.SceneManagement;
#endif

namespace TinyAsset
{
    public class AssetDatabaseLoader : AssetLoader
    {
        public AssetDatabaseLoader(string assetPath, System.Type assetType)
            : base(assetPath, "Assets/" + assetPath, assetType)
        {

        }

        public AssetDatabaseLoader(string assetPath, bool additive, int stack)
            : base(assetPath + stack, "Assets/" + assetPath, additive)
        {

        }

        public override UnityEngine.Object asset { get; protected set; }

        public override Scene scene { get; protected set; }

        protected override AsyncOperation asyncSceneOperation { get; set; }

        protected override void AsyncAssetLoadHandler(string assetName, Type assetType)
        {
#if UNITY_EDITOR
            asset = AssetDatabase.LoadAssetAtPath(assetName, assetType);
#endif
            IsCompleted = true;
        }

        protected override void AsyncSceneLoadHandler(string assetName, LoadSceneParameters parameters)
        {
            if (asyncSceneOperation == null)
            {
#if UNITY_EDITOR
                bool _allowSceneActivation = allowSceneActivation;
                asyncSceneOperation = EditorSceneManager.LoadSceneAsyncInPlayMode(assetName, parameters);
                if (asyncSceneOperation != null)
                    asyncSceneOperation.allowSceneActivation = _allowSceneActivation;
#endif
            }

            if (asyncSceneOperation == null)
            {
                IsCompleted = true;
                return;
            }

            Progress = asyncSceneOperation.progress;
            IsCompleted = asyncSceneOperation.isDone || (asyncSceneOperation.allowSceneActivation == false && asyncSceneOperation.progress == 0.9f);

            if (IsCompleted)
            {
                scene = SceneManager.GetSceneAt(SceneManager.sceneCount - 1);
                asyncSceneOperation = null;
            }
        }

        protected override void SyncAssetLoadHandler(string assetName, Type assetType)
        {
#if UNITY_EDITOR
            asset = AssetDatabase.LoadAssetAtPath(assetName, assetType);
#endif
            IsCompleted = true;
        }

        protected override void SyncSceneLoadHandler(string assetName, LoadSceneParameters parameters)
        {
#if UNITY_EDITOR
            scene = EditorSceneManager.LoadSceneInPlayMode(assetName, parameters);
#endif
            IsCompleted = true;
        }
    }
}